package com.wxzz.elearing.comment.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wxzz.elearing.comment.dto.AnswersDescDto;
import com.wxzz.elearing.comment.entity.Comment;
import com.wxzz.elearing.comment.entity.QuestionsAnswersList;
import com.wxzz.elearing.comment.mapper.QuestionsAnswersListMapper;
import com.wxzz.elearing.comment.service.IAdminQueAnsService;
import com.wxzz.elearing.comment.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.comment.vo.AdminQueAnsVo;
import com.wxzz.elearing.comment.vo.QuestionsContentDescVo;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.wxzz.elearing.comment.service.impl.GiveLikeServiceImpl.GIVELIKECOUNT;
import static com.wxzz.elearing.comment.service.impl.GiveLikeServiceImpl.HEATCOUNT;

@Service
public class AdminQueAnsImpl implements IAdminQueAnsService {


    @Resource
    private QuestionsAnswersListMapper questionsAnswersListMapper;

    @Autowired
    public MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IWxUserApiFeign iWxUserApiFeign;

    public ReturnVO<JgPageVo<List<AdminQueAnsVo>>> answersDescList(AnswersDescDto answersDescDto) {
//        PageHelper.startPage(answersDescDto.getCurPage(), answersDescDto.getMaxPage());
        List<AdminQueAnsVo> list = new ArrayList();
        QuestionsContentDescVo questionsContentDescVo = new QuestionsContentDescVo();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", answersDescDto.getId());
        QuestionsAnswersList questionsAnswersList = questionsAnswersListMapper.selectOne(queryWrapper);

        Integer isAccept = questionsAnswersList.getIsAccept();
        if (isAccept != 0) {
            Query query1 = new Query();
            String acceptId = questionsAnswersList.getAcceptId();
            AdminQueAnsVo comment = mongoTemplate.findById(acceptId, AdminQueAnsVo.class);
            query1.with(new Sort(Sort.Direction.DESC, "createTime")).with(new PageRequest(answersDescDto.getCurPage()-1, answersDescDto.getMaxPage()));
            query1.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()).where("_id").ne(acceptId));
            Query queryCount = new Query();
            queryCount.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()));
            long count = mongoTemplate.count(queryCount, "commentCollection");
            list = mongoTemplate.find(query1, AdminQueAnsVo.class);
            if (answersDescDto.getCurPage() == 1) {
                list.add(0, comment);
                if (list.size() != 1&&list.size()>9) {
                    list.remove(list.size() - 1);
                }
            }
            list.forEach((model)->{
                model.setPublishImageCount(model.getPublishImageUrlList().size());
            });
            JgPageVo jgPageVo = new JgPageVo<>(new PageInfo(list));
            jgPageVo.setCurIndex(answersDescDto.getCurPage());
            jgPageVo.setPageSize(answersDescDto.getMaxPage());
            jgPageVo.setPagesCount((int)Math.ceil(count*1.0/answersDescDto.getMaxPage()));
            jgPageVo.setData(list);
            jgPageVo.setCount(count);

            return new ReturnVO("评论查询成功,采纳已置顶", jgPageVo);
        }
        Query query2 = new Query();
        query2.with(new Sort(Sort.Direction.DESC, "createTime")).with(new PageRequest(answersDescDto.getCurPage()-1, answersDescDto.getMaxPage()));
        query2.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()));
        list = mongoTemplate.find(query2, AdminQueAnsVo.class);
        list.forEach(model->{
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(model.getWxUserId());
            model.setIcon(feignWxUserDto.getIcon());
            model.setNickname(feignWxUserDto.getNickname());
        });
        Query queryCount = new Query();
        queryCount.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()));
        long count = mongoTemplate.count(queryCount, "commentCollection");
        JgPageVo jgPageVo = new JgPageVo<>(new PageInfo(list));
        jgPageVo.setCurIndex(answersDescDto.getCurPage());
        jgPageVo.setPageSize(answersDescDto.getMaxPage());
        jgPageVo.setPagesCount((int) count/answersDescDto.getMaxPage());
        jgPageVo.setData(list);
        jgPageVo.setCount(count);
        return new ReturnVO("评论查询成功", jgPageVo);
    }

    @Override
    public ReturnVO<QuestionsContentDescVo> listAllComment(Long articleId) {
        Map<String, String> map = redisTemplate.opsForHash().entries(HEATCOUNT);
        String heatCount = articleId + ":heat";
        if (map.size() != 0) {
            String s = map.get(heatCount);
            if (StringUtil.isNotBlank(s)) {
                int i = Integer.parseInt(s);
                i += 1;
                redisTemplate.opsForHash().put(HEATCOUNT, heatCount, String.valueOf(i));
            } else {
                redisTemplate.opsForHash().put(HEATCOUNT, heatCount, "1");
            }
        } else {
            redisTemplate.opsForHash().put(HEATCOUNT, heatCount, "1");
        }
        QuestionsContentDescVo questionsContentDescVo = new QuestionsContentDescVo();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", articleId);
        QuestionsAnswersList questionsAnswersList = questionsAnswersListMapper.selectOne(queryWrapper);
        String publishImageUrl = questionsAnswersList.getPublishImageUrl();
//            String s = JSONObject.toJSONString(publishImageUrl);
        List<String> list = JSONObject.parseObject(publishImageUrl, List.class);
        questionsAnswersList.setPublishImageUrlList(list);

        BeanUtils.copyProperties(questionsAnswersList, questionsContentDescVo);

        String artCount = articleId + ":count";
        //获取评论数量
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(articleId));
        questionsContentDescVo.setAnswersCount(mongoTemplate.count(query, "commentCollection"));

        //获取点赞数量
        Map<String, String> map1 = redisTemplate.opsForHash().entries(GIVELIKECOUNT);
        String str = map1.get(artCount);
        if (StringUtil.isNotBlank(str)) {
            int i = Integer.parseInt(str);
            questionsContentDescVo.setGiveLikeCount(i);
        } else {
            questionsContentDescVo.setGiveLikeCount(0);
        }
        //获取热度
        Map<String, String> map2 = redisTemplate.opsForHash().entries(HEATCOUNT);
        String num = map2.get(heatCount);
        if (StringUtil.isNotBlank(num)) {
            int i = Integer.parseInt(num);
            questionsContentDescVo.setHeatCount(i);
        } else {
            questionsContentDescVo.setHeatCount(0);
        }

        return new ReturnVO("文章详情查询成功", questionsContentDescVo);

    }


}
